package com.mipo;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.UpdateResult;
public class Modify {
	public static void main(String[] args) throws Exception {
		/*
		 * 连接到MongoDB服务 如果是远程连接可以替换localhost为服务器所在IP地址 两个参数分别服务器地和端口
		 */
		ServerAddress serverAddress = new ServerAddress("172.31.12.54", 22017);
		List<ServerAddress> addrs = new ArrayList<ServerAddress>();
		addrs.add(serverAddress);
		// 三个参数分别用户名、数据库名、密码
		MongoCredential credential = MongoCredential.createMongoCRCredential("zsmongo", "third_swap_data", "zsmd@017".toCharArray());
		List<MongoCredential> credentials = new ArrayList<MongoCredential>();
		credentials.add(credential);
		// 通过连接认证获取MongoDB连接
		MongoClient mongoClient = new MongoClient(addrs, credentials);
		MongoDatabase db = mongoClient.getDatabase("third_swap_data");
		MongoCollection<Document> users = db.getCollection("c006");
		operation(users);
		mongoClient.close();
	}
    /*各种查询操作，文档如下：*/
	/*{
	    "_id" : ObjectId("5b237d9cd8963733fc7dcd88"),
	    "name" : "hoojo",
	    "age" : 50,
	    "sex" : "男",
	    "children" : {
	        "name" : "jack",
	        "age" : 25,
	        "sex" : "男",
	        "grandSon" : [ 
	            {
	                "name" : "kitty",
	                "age" : 2,
	                "sex" : "男"
	            }, 
	            {
	                "name" : "rose",
	                "age" : 5,
	                "sex" : "男"
	            }
	        ],
	        "grandSon2" : {
	            "name" : "lily"
	        }
	    }
	}*/
	public static void operation(MongoCollection<Document> users) {
		BasicDBObject searchObj = new BasicDBObject();
		searchObj.put("name", "hoojo");
		BasicDBObject newDocument = new BasicDBObject();
		newDocument.put("children.grandSon.0.name", "kitty"); // 修改数组里的数据
		BasicDBObject updateObj = new BasicDBObject();
		updateObj.put("$set", newDocument);
		UpdateResult result = users.updateOne(searchObj, updateObj);
		long updateCount = result.getModifiedCount();
		System.out.println("1:" + updateCount);
		// ================================================
		newDocument = new BasicDBObject();
		newDocument.put("children.grandSon2", ""); // 以为后面是要删除字段，所以第二个参数可以随便填写
		updateObj = new BasicDBObject();
		updateObj.put("$unset", newDocument); // 删除字段
		result = users.updateOne(searchObj, updateObj);
		updateCount = result.getModifiedCount();
		System.out.println("2:" + updateCount);
	}
}
bsondump(导出bson结构)
mongo(客户端,相当于mysql.exe)
mongod(服务端,相当于mysqld.exe)
mongodump(整体数据库导出,二进制,相当于mysqldump)
mongoexport(导出易识别的json文档活csv文档)
mongofiles
mongoimport
mongooplog
mongorestore(数据库整体导入)
mongos(路由器,分片时使用)	
mongostat
mongotop

